package com.service.supply;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.axis2.databinding.types.soapencoding.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.purchase.InquiryMapper;
import com.dao.purchase.ProgramMapper;
import com.dao.purchase.SupplyCompeteDao;
import com.dao.purchase.SupplyCompeteMmDao;
import com.dao.purchase.SupplyCompeteRecordDao;
import com.dao.purchase.SupplyCompeteRecordMmDao;
import com.dao.purchase.SupplyOfferMapper;
import com.dao.purchase.SupplyOfferMmMapper;
import com.dao.supply.InfoMapper;
import com.dao.sys.FileDao;
import com.enums.DealModeEnum;
import com.enums.DictEnum;
import com.model.purchase.CompeteVoModel;
import com.model.purchase.PurchaseInquiry;
import com.model.purchase.PurchaseProgram;
import com.model.purchase.PurchaseSupplyOffer;
import com.model.purchase.PurchaseSupplyOfferMm;
import com.model.purchase.SupplyCompeteMmModel;
import com.model.purchase.SupplyCompeteModel;
import com.model.purchase.SupplyCompeteRecordMmModel;
import com.model.purchase.SupplyCompeteRecordModel;
import com.model.supply.SupplyInfoModel;
import com.model.supply.SupplyUserModel;
import com.model.sys.FileModel;
import com.model.sys.SysDict;
import com.model.sys.SysUser;
import com.mysql.cj.xdevapi.Result;
import com.service.sys.SysDictService;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;

@Service
public class SupplyCompeteService {
	static final Logger logger = LoggerFactory.getLogger(SupplyCompeteService.class);

	@Autowired
	SupplyCompeteDao supplyCompeteDao;
	@Autowired
	SupplyCompeteMmDao competeMmDao;
	@Autowired
	SupplyCompeteRecordDao competeRecordDao;
	@Autowired
	SupplyCompeteRecordMmDao competeRecordMmDao;
	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	InfoMapper infoMapper;
	@Autowired
	FileDao fileDao;
	@Autowired
	SupplyOfferMapper supplyOfferMapper;
	@Autowired
	SupplyOfferMmMapper supplyOfferMmMapper;
	@Autowired
	ProgramMapper programMapper;

	@Value("${filepath}")
	String basePath;
	@Autowired
	SysDictService sysDictService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		queryMap.put("infId", supplyUserModel.getInfId());

		List<SupplyCompeteModel> list = supplyCompeteDao.selectList(queryMap);
		int count = supplyCompeteDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String inqId) {
		HttpResult httpResult = new HttpResult();
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();

		SupplyCompeteModel supplyCompeteModel = supplyCompeteDao.load(supplyUserModel.getInfId(), inqId);
		CompeteVoModel competeVoModel = new CompeteVoModel();
		BeanUtils.copyProperties(supplyCompeteModel, competeVoModel);

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", supplyUserModel.getInfId());
		infoHashMap.put("inqId", inqId);
		List<SupplyCompeteMmModel> competeMmModels = competeMmDao.selectList(infoHashMap);
		competeVoModel.setSupplyCompeteMmModels(competeMmModels);

		httpResult.setData(supplyCompeteModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	public HttpResult selectRank(String inqId) {
		if (StringUtils.isNullOrEmpty(inqId)) {
			return HttpResult.error("参数为空");
		}
		HttpResult httpResult = new HttpResult();
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		CompeteVoModel competeVoModel = new CompeteVoModel();

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("inqId", inqId);
		infoHashMap.put("order", "desc");
		infoHashMap.put("sort", "inqOfrTime");

		List<SupplyCompeteModel> rankCompeteModels = new ArrayList<SupplyCompeteModel>();
		List<SupplyCompeteMmModel> rankCompeteMmModels = new ArrayList<SupplyCompeteMmModel>();
		List<SupplyCompeteModel> infCompeteModels = supplyCompeteDao.selectList(infoHashMap);

		// 获取已报价供应商,从记录表查询最后一条报价记录，放入list中排名
		for (Iterator iterator = infCompeteModels.iterator(); iterator.hasNext();) {
			SupplyCompeteModel supplyCompeteModel = (SupplyCompeteModel) iterator.next();
			infoHashMap.put("infId", supplyCompeteModel.getInfId());
			SupplyCompeteModel ofrtimeModel = supplyCompeteDao.load(supplyCompeteModel.getInfId(), inqId);
			List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(infoHashMap);
			if (competeRecordModels.size() > 0) {
				SupplyCompeteModel supplyCompeteModel2 = new SupplyCompeteModel();
				BeanUtils.copyProperties(competeRecordModels.get(0), supplyCompeteModel2);
				rankCompeteModels.add(supplyCompeteModel2);

				// 明细记录表 查询相应得明细记录，放入list排名
				HashMap<String, Object> mHashMap = new HashMap<String, Object>();
				mHashMap.putAll(infoHashMap);
				mHashMap.put("comUuid", competeRecordModels.get(0).getComUuid());
				List<SupplyCompeteRecordMmModel> competeRecordMmModels = competeRecordMmDao.selectList(mHashMap);
				for (Iterator mmIterator = competeRecordMmModels.iterator(); mmIterator.hasNext();) {
					SupplyCompeteRecordMmModel supplyCompeteMmModel = (SupplyCompeteRecordMmModel) mmIterator.next();
					SupplyCompeteMmModel supplyCompeteMmModel2 = new SupplyCompeteMmModel();
					BeanUtils.copyProperties(supplyCompeteMmModel, supplyCompeteMmModel2);
					// 只有提交报价才参与排名
					if (StringUtils.isNotNull(ofrtimeModel.getInqOfrTime())) {
						supplyCompeteMmModel2.setInqOfrTime(ofrtimeModel.getInqOfrTime());
						rankCompeteMmModels.add(supplyCompeteMmModel2);
					}
				}
			}
		}

		rankCompeteModels = rankCompeteModels.stream().filter(s -> s.getInqOfrTotalPrice() != null)
				.collect(Collectors.toList());
		rankCompeteModels = rankCompeteModels.stream().sorted(Comparator
				.comparing(SupplyCompeteModel::getInqOfrTotalPrice).thenComparing(SupplyCompeteModel::getUpdateTime))
				.collect(Collectors.toList());
		int rank = 1;
		for (SupplyCompeteModel supplyCompeteModel : rankCompeteModels) {
			supplyCompeteModel.setRank((rank++) + "");
			if (supplyCompeteModel.getInfId().equals(supplyUserModel.getInfId())) {
				BeanUtils.copyProperties(supplyCompeteModel, competeVoModel);
			}
		}

		// 所有供应商所有物资排序后，生成序号，返回本供应商
		rankCompeteMmModels = rankCompeteMmModels.stream().filter(s -> s.getInqOfrTotalPrice() != null)
				.collect(Collectors.toList());
		rankCompeteMmModels = rankCompeteMmModels.stream()
				.sorted(Comparator.comparing(SupplyCompeteMmModel::getPlanId)
						.thenComparing(SupplyCompeteMmModel::getInqOfrUnitPrice)
						.thenComparing(SupplyCompeteMmModel::getInqOfrTime))
				.collect(Collectors.toList());

		int rankMm = 0;
		String planIdString = "";
		List<SupplyCompeteMmModel> competeMmModels1 = new ArrayList<SupplyCompeteMmModel>();
		for (Iterator<SupplyCompeteMmModel> iteratorMm = rankCompeteMmModels.iterator(); iteratorMm.hasNext();) {
			SupplyCompeteMmModel supplyCompeteMmModel = (SupplyCompeteMmModel) iteratorMm.next();
			if (StringUtils.isNullOrEmpty(planIdString)) {
				planIdString = supplyCompeteMmModel.getPlanId();// 用第一条初始化
			}

			if (supplyCompeteMmModel.getPlanId().equals(planIdString)) {
				rankMm++;
			} else {// 当物资切换时
				planIdString = supplyCompeteMmModel.getPlanId();
				rankMm = 1;
			}
			supplyCompeteMmModel.setRank(rankMm + "");
			if (supplyCompeteMmModel.getInfId().equals(supplyUserModel.getInfId())) {
				competeMmModels1.add(supplyCompeteMmModel);
			}
		}

		competeVoModel.setSupplyCompeteMmModels(competeMmModels1);

		httpResult.setData(competeVoModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	public HttpResult save(CompeteVoModel competeVoModel) {
		if (competeVoModel == null || competeVoModel.getSupplyCompeteMmModels() == null) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(competeVoModel.getInqId());
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可操作!");
		}
		if (competeVoModel.getInqStartTime().compareTo(DateUtils.getCurrentTime()) > 0) {
			return HttpResult.error("报价未开始，不可操作!");
		}
		if (competeVoModel.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return HttpResult.error("当前会话不存在！");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在！");
		}
		if (competeVoModel.getInqOfrNum().doubleValue() <= 0
				|| competeVoModel.getInqOfrTotalPrice().doubleValue() <= 0) {
			return HttpResult.error("报价数量和价格不能为空！");
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("infId", supplyUserModel.getInfId());
		hashMap.put("inqId", competeVoModel.getInqId());

		PurchaseProgram purchaseProgram = programMapper.load(competeVoModel.getGramId());
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(hashMap);
		if (purchaseProgram.getGramTimes() > 0) {
			if (purchaseProgram.getGramTimes() < (competeRecordModels.size() + 1)) {
				return HttpResult.error("已超过报价次数！");
			}
		}

		if (purchaseProgram.getGramDealMode().equals(DealModeEnum.all.getValue())) {// 总价成交
			if (competeRecordModels.size() > 0) {
				SupplyCompeteRecordModel lastRecordModel = competeRecordModels.get(0);
				BigDecimal lastBigDecimal = lastRecordModel.getInqOfrTotalPrice();
				if (lastBigDecimal.compareTo(competeVoModel.getInqOfrTotalPrice()) <= 0) {
					return HttpResult.error("总价比上次报价上涨，请重新维护报价！");
				}
			}
		}
//		else {// 分项中标：每个物资判断价格范围
		if (competeRecordModels.size() > 0) {
			SupplyCompeteRecordModel lastRecordModel = competeRecordModels.get(0);
			hashMap.put("comUuid", lastRecordModel.getComUuid());
			List<SupplyCompeteRecordMmModel> lastCompeteRecordMmModels = competeRecordMmDao.selectList(hashMap);
			if (lastCompeteRecordMmModels.size() > 0) {
				for (Iterator iterator = lastCompeteRecordMmModels.iterator(); iterator.hasNext();) {
					SupplyCompeteRecordMmModel supplyCompeteRecordMmModel = (SupplyCompeteRecordMmModel) iterator
							.next();
					BigDecimal lastBigDecimal = supplyCompeteRecordMmModel.getInqOfrUnitPrice();
					for (SupplyCompeteMmModel competeMmModel : competeVoModel.getSupplyCompeteMmModels()) {
						if (competeMmModel.getPlanId().equals(supplyCompeteRecordMmModel.getPlanId())) {
							if (lastBigDecimal.compareTo(competeMmModel.getInqOfrUnitPrice()) <= 0) {
								return HttpResult.error("物资：" + competeMmModel.getMmDetail() + "报价单价只能下降，请重新维护报价！");
							} else if (lastBigDecimal.compareTo(competeMmModel.getInqOfrUnitPrice()) == 0) {
								// 当报价没有改变时，提交时间按照上次来，因为排名按照提交时间来
								competeMmModel.setCreateTime(supplyCompeteRecordMmModel.getCreateTime());
								competeMmModel.setInqOfrTime(DateUtils.getCurrentMillTime());
							} else {
								competeMmModel.setCreateTime(DateUtils.getCurrentTime());
								competeMmModel.setInqOfrTime(DateUtils.getCurrentMillTime());
							}
						}
					}
				}
			}
		}
//		}

		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = supplyCompeteDao.update(competeVoModel);
		for (SupplyCompeteMmModel mmModel : competeVoModel.getSupplyCompeteMmModels()) {
			result += competeMmDao.update(mmModel);
		}
		// 记录保存

		if (result > 0) {
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(competeVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult commit(CompeteVoModel competeVoModel) {
		if (competeVoModel == null) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在！");
		}
		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", supplyUserModel.getInfId());
		List<SupplyInfoModel> infoModels = infoMapper.selectList(infoHashMap);
		if (infoModels.size() == 0) {
			return HttpResult.error("供应商不存在");
		}
		// 设置提交时间
		competeVoModel.setInqOfrTime(DateUtils.getCurrentMillTime());
		String mailString = infoModels.get(0).getInfMail();
		if (StringUtils.isNullOrEmpty(mailString)) {
			return HttpResult.error("请先在档案信息维护正确邮箱!");
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;

		SupplyCompeteRecordModel competeRecordModel = new SupplyCompeteRecordModel();
		BeanUtils.copyProperties(competeVoModel, competeRecordModel);
		competeRecordModel.setComUuid(UUID.randomUUID().toString());
		result += competeRecordDao.insert(competeRecordModel);

		for (SupplyCompeteMmModel mmModel : competeVoModel.getSupplyCompeteMmModels()) {
			mmModel.setInqOfrTime(competeVoModel.getInqOfrTime());
			result += competeMmDao.update(mmModel);
			SupplyCompeteRecordMmModel recordMmModel = new SupplyCompeteRecordMmModel();
			BeanUtils.copyProperties(mmModel, recordMmModel);
			recordMmModel.setInqOfrTime(competeVoModel.getInqOfrTime());
			recordMmModel.setComUuid(competeRecordModel.getComUuid());
			recordMmModel.setCreateId(supplyUserModel.getCreateId());
			recordMmModel.setCreateName(supplyUserModel.getCreateName());
			recordMmModel.setCreateTime(DateUtils.getCurrentTime());
			result += competeRecordMmDao.insert(recordMmModel);
		}

		// 当最后一次报价时
		infoHashMap.put("inqId", competeVoModel.getInqId());
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(infoHashMap);
		PurchaseProgram purchaseProgram = programMapper.load(competeVoModel.getGramId());
		if (purchaseProgram.getGramTimes() > 0) {
			if (purchaseProgram.getGramTimes() == competeRecordModels.size()) {
				competeVoModel.setStatus(Global.YES + "");
				result += supplyCompeteDao.update(competeVoModel);
				insertOffer(competeVoModel);
			}
		} else {
			competeVoModel.setStatus(Global.NO + "");
			result += supplyCompeteDao.update(competeVoModel);
		}

		if (result > 0) {
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(competeVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 完成竞价
	 * 
	 * @param competeVoModel
	 * @return
	 */
	@Transactional
	public HttpResult finish(SupplyCompeteModel competeModel) {
		if (competeModel == null) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在！");
		}
		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", supplyUserModel.getInfId());

		List<SupplyInfoModel> infoModels = infoMapper.selectList(infoHashMap);
		if (infoModels.size() == 0) {
			return HttpResult.error("供应商不存在");
		}

		infoHashMap.put("inqId", competeModel.getInqId());
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(infoHashMap);
		if (competeRecordModels.size() == 0) {
			return HttpResult.error("请先提交一次报价！");
		}
		PurchaseProgram purchaseProgram = programMapper.load(competeModel.getGramId());
		if (purchaseProgram.getGramTimes() > 0) {
			if (purchaseProgram.getGramTimes() < competeRecordModels.size()) {
				return HttpResult.error("已超过报价次数！");
			}
		}

		competeModel = supplyCompeteDao.load(supplyUserModel.getInfId(), competeModel.getInqId());
		if (competeModel == null) {
			return HttpResult.error("不存在此数据");
		}
		if (competeModel.getStatus().equals(Global.YES + "")) {
			return HttpResult.error("数据已提交！");
		}
		String mailString = infoModels.get(0).getInfMail();
		if (StringUtils.isNullOrEmpty(mailString)) {
			return HttpResult.error("请先在档案信息维护正确邮箱!");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(competeModel.getInqId());
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可操作!");
		}
		if (competeModel.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;

		competeModel.setInqOfrTime(DateUtils.getCurrentMillTime());// 设置提交时间
		competeModel.setStatus(Global.YES + "");
		result = supplyCompeteDao.update(competeModel);

		CompeteVoModel competeVoModel = new CompeteVoModel();
		List<SupplyCompeteMmModel> competeMmModels = competeMmDao.selectList(infoHashMap);
		BeanUtils.copyProperties(competeModel, competeVoModel);
		competeVoModel.setSupplyCompeteMmModels(competeMmModels);
		for (SupplyCompeteMmModel mmModel : competeVoModel.getSupplyCompeteMmModels()) {
			mmModel.setStatus(Global.YES + "");
			mmModel.setInqOfrTime(DateUtils.getCurrentMillTime());
			result += competeMmDao.update(mmModel);
		}
		result += insertOffer(competeVoModel);

		if (result > 0) {
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(competeVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(competeVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	private int insertOffer(CompeteVoModel competeVoModel) {
		int result = 0;
		// 保存至报价表
		PurchaseSupplyOffer purchaseSupplyOffer = new PurchaseSupplyOffer();
		purchaseSupplyOffer.setCreateTime(DateUtils.getCurrentTime());
		BeanUtils.copyProperties(competeVoModel, purchaseSupplyOffer);
		if (supplyOfferMapper.update(purchaseSupplyOffer) == 0) {
			purchaseSupplyOffer.setInqOfrTime(DateUtils.getCurrentMillTime());
			result += supplyOfferMapper.insert(purchaseSupplyOffer);
		}
		for (Iterator iterator = competeVoModel.getSupplyCompeteMmModels().iterator(); iterator.hasNext();) {
			SupplyCompeteMmModel supplyCompeteMmModel = (SupplyCompeteMmModel) iterator.next();
			PurchaseSupplyOfferMm purchaseSupplyOfferMm = new PurchaseSupplyOfferMm();
			BeanUtils.copyProperties(supplyCompeteMmModel, purchaseSupplyOfferMm);
			if (supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm) == 0) {
				result += supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
			}
		}
		return result;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String infId, String inqId) {
		if (!StringUtils.isNotNull(infId) || !StringUtils.isNotNull(inqId)) {
			return HttpResult.error("参数不能为空");
		}
		SupplyCompeteModel model = supplyCompeteDao.load(infId, inqId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
//		int result = supplyCompeteDao.delete(infId, inqId);
//		if (result > 0) {
//			httpResult.setMsg("删除成功！");
//		} else {
//			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
//			httpResult.setMsg("不存在此条数据！");
//		}
		return httpResult;
	}

	public HttpResult updataLowStatus(String inqId, String planId) {
		if (!StringUtils.isNotNull(inqId) || !StringUtils.isNotNull(planId)) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在！");
		}
		SupplyCompeteModel model = supplyCompeteDao.load(supplyUserModel.getInfId(), inqId);
		List<SupplyCompeteMmModel> rankCompeteMmModels = new ArrayList<SupplyCompeteMmModel>();
		if (!model.getLowStatus().equals(Global.YES + "")) {
			return HttpResult.error("非竞价跟进状态，不可操作！");
		}
		if (model.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		int result = 0;

		CompeteVoModel competeVoModel = new CompeteVoModel();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("infId", supplyUserModel.getInfId());
		hashMap.put("inqId", inqId);
		hashMap.put("order", "desc");
		hashMap.put("sort", "inqOfrTime");
		// 从报价记录中找到最后一条报价记录，价格改为其他供应商最低报价
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(hashMap);
		if (competeRecordModels.size() > 0) {
			SupplyCompeteRecordModel newRecordModel = competeRecordModels.get(0);
			newRecordModel.setCreateTime(DateUtils.getCurrentTime());
			newRecordModel.setInqOfrNum(BigDecimal.ZERO);// 数量初始化
			newRecordModel.setInqOfrTotalPrice(BigDecimal.ZERO);// 数量初始化
			newRecordModel.setInqOfrTime(DateUtils.getCurrentMillTime());// 设置提交时间
			BeanUtils.copyProperties(newRecordModel, competeVoModel);

			HashMap<String, Object> mHashMap = new HashMap<String, Object>();
			mHashMap.putAll(hashMap);
			mHashMap.put("comUuid", competeRecordModels.get(0).getComUuid());
			List<SupplyCompeteRecordMmModel> competeRecordMmModels = competeRecordMmDao.selectList(mHashMap);
			newRecordModel.setComUuid(UUID.randomUUID().toString());
			for (SupplyCompeteRecordMmModel newMmModel : competeRecordMmModels) {
				newMmModel.setComUuid(newRecordModel.getComUuid());
				// 获取本物资最低价格
				if (newMmModel.getPlanId().equals(planId)) {
					HashMap<String, Object> offerHashMap = new HashMap<String, Object>();
					offerHashMap.put("inqId", inqId);
					offerHashMap.put("planId", planId);
					List<PurchaseSupplyOfferMm> supplyOfferMms = supplyOfferMmMapper.selectAll(offerHashMap);
					supplyOfferMms = supplyOfferMms.stream()
							.sorted(Comparator.comparing(PurchaseSupplyOfferMm::getInqOfrUnitPrice,
									Comparator.nullsLast(Comparator.naturalOrder())))
							.collect(Collectors.toList());
					if (newMmModel.getInqOfrUnitPrice().compareTo(supplyOfferMms.get(0).getInqOfrUnitPrice()) == 0) {
						return HttpResult.error("已是最低价，无需跟进！");
					}
					newMmModel.setInqOfrUnitPrice(supplyOfferMms.get(0).getInqOfrUnitPrice());
					int rank = 1;
					for (PurchaseSupplyOfferMm supplyOfferMm : supplyOfferMms) {
						if (newMmModel.getInqOfrUnitPrice().compareTo(supplyOfferMm.getInqOfrUnitPrice()) == 0) {
							rank++;// 计算已经有多少个最低价，按照顺序得到排名
						}
					}
					newMmModel.setInqOfrTotalPrice(newMmModel.getInqOfrNum().multiply(newMmModel.getInqOfrUnitPrice()));
					newMmModel.setRank(rank + "");
					newMmModel.setCreateTime(DateUtils.getCurrentTime());
					newMmModel.setInqOfrTime(DateUtils.getCurrentMillTime());// 设置提交时间
				}
				result += competeRecordMmDao.insert(newMmModel);
				// 生成物资明细
				SupplyCompeteMmModel competeMmModel = new SupplyCompeteMmModel();
				BeanUtils.copyProperties(newMmModel, competeMmModel);
				result += competeMmDao.update(competeMmModel);
				competeMmModel.setCreateId("");
				competeMmModel.setCreateName("");
				competeMmModel.setCreateTime(DateUtils.getCurrentMillTime());
				rankCompeteMmModels.add(competeMmModel);
				// 计算合计值
				newRecordModel.setInqOfrNum(newMmModel.getInqOfrNum().add(newRecordModel.getInqOfrNum()));
				newRecordModel.setInqOfrTotalPrice(
						newMmModel.getInqOfrTotalPrice().add(newRecordModel.getInqOfrTotalPrice()));
			}
			result += competeRecordDao.insert(newRecordModel);
			competeVoModel.setInqOfrNum(newRecordModel.getInqOfrNum());// 数量初始化
			competeVoModel.setInqOfrTotalPrice(newRecordModel.getInqOfrTotalPrice());// 数量初始化
			competeVoModel.setSupplyCompeteMmModels(rankCompeteMmModels);
			competeVoModel.setCreateId("");
			competeVoModel.setCreateName("");
			competeVoModel.setCreateTime(DateUtils.getCurrentMillTime());
			result += supplyCompeteDao.update(competeVoModel);

			// 修改揭示后数据
			result += insertOffer(competeVoModel);
		}

		HttpResult httpResult = new HttpResult();

		if (result > 0) {
//			httpResult.setData(competeVoModel);
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	public HttpResult back(String inqId) {
		if (!StringUtils.isNotNull(inqId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqId);
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可回退!");
		}
		if (purchaseInquiry.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();

		SupplyCompeteModel model = supplyCompeteDao.load(supplyUserModel.getInfId(), inqId);
		if (model == null) {
			return HttpResult.error("数据不存在!");
		}

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", supplyUserModel.getInfId());
		infoHashMap.put("inqId", inqId);
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectList(infoHashMap);
		PurchaseProgram purchaseProgram = programMapper.load(model.getGramId());
		if (purchaseProgram.getGramTimes() > 0) {
			if (purchaseProgram.getGramTimes() < competeRecordModels.size()) {
				return HttpResult.error("已超过报价次数！");
			}
		}
		//
		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = supplyCompeteDao.update(model);

		if (result > 0) {
			httpResult.setMsg("撤回成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<SupplyCompeteModel> list = supplyCompeteDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), SupplyCompeteModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}
	}

	/**
	 * 导入报价信息
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult importMM(Map<String, Object> map) {
		List<FileModel> fileModels = fileDao.selectList(map);
		if (fileModels == null || fileModels.size() == 0) {
			return HttpResult.error("导入文件不存在!");
		}

		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		SupplyCompeteModel competeModel = supplyCompeteDao.load(map.get("fileRow").toString(),
				supplyUserModel.getInfId());
		if (competeModel.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		List<SysDict> dicList = sysDictService.queryItemByTypeName(DictEnum.taxString);

		FileModel fileModel = fileModels.get(0);
		String fileName = basePath + "/" + fileModel.getFileUrl() + "/" + fileModel.getFileId() + "-"
				+ fileModel.getFileName();
		List<String> errList = new ArrayList<String>();
		EasyExcel.read(fileName, PurchaseSupplyOfferMm.class, new PageReadListener<PurchaseSupplyOfferMm>(dataList -> {
			for (PurchaseSupplyOfferMm demoData : dataList) {
				if (demoData.getPlanId() == null) {
					errList.add("计划编码：" + demoData.getMmDetail() + "为空");
					break;
				}
				SupplyCompeteMmModel purchaseSupplyOfferMm = competeMmDao.load(supplyUserModel.getInfId(),
						map.get("fileRow").toString(), demoData.getPlanId());
				if (purchaseSupplyOfferMm == null) {
					errList.add("计划编码：" + demoData.getMmDetail() + "不存在");
					break;
				}
				if (demoData.getInqOfrNum() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价数量为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrNum(demoData.getInqOfrNum());
				if (demoData.getInqOfrUnitPrice() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价单价为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrUnitPrice(demoData.getInqOfrUnitPrice());
				purchaseSupplyOfferMm
						.setInqOfrTotalPrice(demoData.getInqOfrNum().multiply(demoData.getInqOfrUnitPrice()));
				purchaseSupplyOfferMm.setInqDeliverDate(demoData.getInqDeliverDate());
				SysDict sysDict = existsDic(demoData.getInqTaxRate(), dicList);
				if (sysDict == null) {
					errList.add("计划编码：" + demoData.getPlanId() + "税率录入不正确");
				} else {
					purchaseSupplyOfferMm.setInqTaxNum(sysDict.getDicValue());
//					BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
					purchaseSupplyOfferMm.setInqTaxRate(sysDict.getDicName());
				}
				competeMmDao.update(purchaseSupplyOfferMm);
			}
		})).sheet().doRead();
		if (errList.size() > 0) {
			HttpResult httpResult = new HttpResult();
			httpResult.setData(errList);
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			return httpResult;
		}
		return HttpResult.ok("导入成功");
	}

	public SysDict existsDic(String dicString, List<SysDict> dicList) {
		SysDict flag = null;
		for (SysDict sysDict : dicList) {
//			BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
			if (sysDict.getDicName().equals(dicString)) {
				return sysDict;
			}
		}
		return flag;

	}
}
